﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

using DragDraw.UserService;
using DragDraw.Util;

namespace DragDraw.Tool
{
    public partial class FileManager : UserControl
    {
        internal WidgetServiceProxy ServiceProxy;
        private FileManagerDesc m_fmd = new FileManagerDesc();

        private FileInfo m_uploadFile;

        public FileManager()
        {
            InitializeComponent();
            if (WidgetHelper.IsInMySpace == false)
                BtnUpload.Visibility = Visibility.Collapsed;
            UploadPanel.Visibility = Visibility.Collapsed;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            ServiceProxy = OperationManager.Instance.CreateWidgetServiceProxy(this);
            ServiceProxy.SaveFileCompleted += new EventHandler<OpenWriteCompletedEventArgs>(ServiceProxy_SaveFileCompleted);
            ServiceProxy.GetSessionCompleted += new EventHandler<GetSessionCompletedEventArgs>(ServiceProxy_GetSessionCompleted);
            ServiceProxy.GetSession("files");
        }

        void ServiceProxy_GetSessionCompleted(object sender, GetSessionCompletedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.Result))
                return;
            try
            {
                XmlSerializer xs = new XmlSerializer(typeof(FileManagerDesc));
                XmlReader xr = XmlReader.Create(new StringReader(e.Result));

                m_fmd = (FileManagerDesc)xs.Deserialize(xr);
            }
            catch { }
            ListFile.ItemsSource = m_fmd.Files;
        }

        void ServiceProxy_SaveFileCompleted(object sender, OpenWriteCompletedEventArgs e)
        {
            //将图片数据流发送到服务器上
            TbUploadMessage.Text = "上传中，可以选择关闭取消上传";

            Stream outputStream = e.Result;
            //ErrorManager.Instance.ShowDebugMessage((string)((object[])(e.UserState)[1]));

            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            using (Stream inputStream = m_uploadFile.OpenRead())
            {
                while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    outputStream.Write(buffer, 0, bytesRead);
                }
            }
            outputStream.Close();
            HtmlPage.Window.Alert("文件上传成功!!!");
            m_fmd.Files.Add(
                new FileDesc() 
                {
                    FileName = m_uploadFile.Name,
                    FileUrl = WidgetHelper.MapFileUrl(m_uploadFile.Name) 
                }
            );
            m_uploadFile = null;
            UploadPanel.Visibility = Visibility.Collapsed;
            ListFile.ItemsSource = m_fmd.Files.ToArray();
            SaveDesc();
        }

        private void SaveDesc()
        {
            string ret = WidgetHelper.ObjectToXml(m_fmd, typeof(FileManagerDesc));
            ServiceProxy.SetSession("files", ret);
        }

        private void BtnDownload_Click(object sender, RoutedEventArgs e)
        {
            if (ListFile.SelectedItem != null)
            {
                FileDesc fd = (FileDesc)ListFile.SelectedItem;
                HtmlPage.Window.Navigate(new Uri(
                    WidgetHelper.MapFileUrl(OperationManager.Instance.
                    CurrentSpace.OwnerUserID,fd.FileName)), "_blank");
            }
        }

        private void BtnUpload_Click(object sender, RoutedEventArgs e)
        {
            m_uploadFile = null;
            ButtonPanel.Visibility = Visibility.Visible;
            UploadPanel.Visibility = Visibility.Visible;
            TbUploadMessage.Text = "";
            TxtPath.Text = "";
        }

        private void BtnUploadOk_Click(object sender, RoutedEventArgs e)
        {
            if (m_uploadFile == null)
            {
                ErrorManager.Instance.ShowWarnMessage("请先选择文件再上传");
                return;
            }
            ButtonPanel.Visibility = Visibility.Collapsed;
            ServiceProxy.SaveFile(m_uploadFile.Name);
        }

        private void BtnBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            if (dialog.ShowDialog() == true)
            {
                TxtPath.Text = dialog.File.Name;
            }
            m_uploadFile = dialog.File;
        }

        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            UploadPanel.Visibility = Visibility.Collapsed;
            m_uploadFile = null;
        }
    }

    public class FileManagerDesc
    {
        public List<FileDesc> Files { get; set; }
        public FileManagerDesc()
        {
            Files = new List<FileDesc>();
        }
    }

    public class FileDesc
    {
        public string FileName { get; set; }
        public string FileUrl { get; set; }
    }
}
